var app = getApp()
Page({
  data: {
    show: false,
    imgList: [],
    download_detail: null,
    getComments: 0
  },



  onLoad(option) {
    var download_detail = JSON.parse(option.item)
    this.setData({
      download_detail: download_detail
    })
    this.getFileUrl(download_detail)
  },
  onReady() {
    this.setData({
      show: true,
    })
  },
  getFileUrl(download_detail) {
    var idList = []
    var that = this
    for (var i = 0; i < download_detail.cloud_imageID.length; i++) {
      var fileid = download_detail.cloud_imageID[i]
      var data = {
        fileid: fileid,
        max_age: 7200
      }
      idList[i] = data
    }
    //console.log(idList)
    qq.request({//请求拼装好的
      url: 'https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=' + app.globalData.access_token,
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "file_list": idList
      },
      success(res) {
        //console.log(res)
        that.setData({
          imgList: res.data.file_list
        })
      }
    })
  },
  toRate(e) {
    var num = this.data.download_detail.rateNum
    var len = this.data.download_detail.rate.length
    var haverate = num - len
    if(haverate){
      qq.showToast({
        icon:'none',
        title:'您已经评过分啦！'
      })
    }else{
    var rate = e.currentTarget.dataset.rate+1
    var that = this
    qq.showModal({
      title: '确定评论？',
      content: '您将给此资料评论' + (rate) + '颗星',
      success(res) {
        if (res.confirm) {
          //console.log("s")
          that.updateDB(rate)
        }
      }
    })
    }
  },
  updateDB(rate) {
    var that = this
       qq.request({
      url: 'https://api.weixin.qq.com/tcb/databaseupdate?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"download\").doc(\"" + that.data.download_detail._id+ "\").update({\
        data: {\
               rate: db.command.push(["+rate+"])\
               }\
         })"
      },  
      success(res) {
        //console.log(res)
        that.setData({
          'download_detail.avgRate':rate,
          'download_detail.rateNum':that.data.download_detail.rateNum+1
        })
        //console.log(rate,res)
        qq.showToast({
          title: "感谢您的评分！"
        })
      },
      fail(msg) {
        //console.log(msg)
      }
    })
  },
  ViewImage(e) {
    var urls = []
    var imgList = this.data.imgList
    for (var i = 0; i < imgList.length; i++) {
      urls[i] = imgList[i].download_url
    }
    qq.previewImage({
      urls: urls,
      current: e.currentTarget.dataset.url
    });
  }
})